<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:scrollX}"
        :components="draggableComponent"
        bordered
        rowKey="key"
        :columns="dragResizeColumns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="null"
        :class="'j-table-force-nowrap'"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record" v-if="!disabled || !kpButtonDisabled">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            @click="handleEdit(record)"
          />
        </span>

      </a-table>
    </div>

    <ErpFinanceInvoiceTaxRateRecordModal ref="modalForm"  @ok="modalFormOk" @dataOne="dataOne"></ErpFinanceInvoiceTaxRateRecordModal>

    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import ErpFinanceInvoiceTaxRateRecordModal from './modules/ErpFinanceInvoiceTaxRateRecordModal'
  import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
  import AuditModal from '@/views/scy/components/AuditModal'
  import { filterObj } from '@/utils/util'
  import { getAction } from '@/api/manage'
  import Vue from 'vue'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
  import { DragResizable } from '@/mixins/DragResizable'

  export default {
    name: 'ErpFinanceInvoiceExpensesDetailList',
    mixins: [mixinDevice, DisabledAuthFilterMixin, DragResizable],
    components: {
      ErpProjectReportModal,
      ErpFinanceInvoiceTaxRateRecordModal,
      AuditModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      kpButtonDisabled: {
        type: Boolean,
        default: true,
        required: false
      },
      isCancel:{
        type: String,
        default: '0',
        required: false
      }
    },
    data () {
      return {
        params: {
          billId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '开票费用信息页面',
        // 表头
        dragResizeColumns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '税率（%）',
            align: 'center',
            dataIndex: 'taxRate',
            width: 170,
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['contractRateType'], text + '')
              }
            }
          },
          {
            title: '应开票金额（元）',
            align: 'center',
            dataIndex: 'shouldInvoiceAmount',
            width: 170,
            ellipsis: true
          },
          {
            title: '已开票金额（元）',
            align: 'center',
            dataIndex: 'onInvoiceAmount',
            width: 170,
            ellipsis: true
          },
          {
            title: '本次开票金额（元）',
            align: 'center',
            dataIndex: 'invoiceAmount',
            width: 170,
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 110,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/finance/invoice/erpFinanceInvoiceTaxRateRecord/allList',
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById'
        },
        dictOptions: {},
        superFieldList: [],
        projectId: null
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        // this.loadData()
        this.initColumns()
      }
      console.log("this.disabled",this.disabled,"this.formBpm",this.formBpm,"kpButtonDisabled",this.kpButtonDisabled);
      this.dragResizeColumnswidth = this.dragResizeColumns.map(val => {
        return val.width
      })
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    computed: {
    },
    methods: {
      resetting() {
        this.dragResizeColumns.forEach((val, index) => {
          val.width = this.dragResizeColumnswidth[index]
        })
      },
      async initDictConfig() {
        // 税率
        initDictOptions('contract_rate_type').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'contractRateType', res.result)
          }
        })
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'projectId', text: '项目编号', dictCode: '' })
        fieldList.push({ type: 'BigDecimal', value: 'itemMoney', text: '款项金额', dictCode: '' })
        fieldList.push({ type: 'date', value: 'estimateRefundTime', text: '预计回款时间' })
        fieldList.push({ type: 'string', value: 'projectProgress', text: '项目进度', dictCode: '' })
        // fieldList.push({type:'int',value:'teamYear',text:'费用所属年度',dictCode:''})
        fieldList.push({ type: 'int', value: 'teamId', text: '经营团队', dictCode: '' })
        fieldList.push({ type: 'string', value: 'undertaker', text: '团队负责人', dictCode: '' })
        fieldList.push({ type: 'string', value: 'attributionYear', text: '所属年度', dictCode: '' })
        fieldList.push({ type: 'BigDecimal', value: 'invoiceAmount', text: '开票金额', dictCode: '' })
        // fieldList.push({type:'string',value:'invoiceCategory',text:'开票类型',dictCode:''})
        this.superFieldList = fieldList
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            console.log("11111111111",this.dataSource)
            this.onData()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.dragResizeColumns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (id) {
        console.log('handleDelete this.projectId---->', this.projectId)
        if (this.dataSource.length == 1) {
          this.dataSource = []
          this.onData()
          this.$emit('changeBuyerUnit', null);
          return
        }
        for (let i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i].id == id) {
            this.dataSource.splice(i, 1);
          }
        }
        // this.dataSource.splice(key,1);
        // this.dataSource.forEach((item, index) => {
        //   item.key = index
        // })
        // 如果删除了第一个元素则修改业主单位
        if (this.projectId !== this.dataSource[0].projectId) {
          this.projectId = this.dataSource[0].projectId
          this.$emit('changeBuyerUnit', this.dataSource[0]);
        }
        this.onData()
      },
      handleEdit: function (record) {
        if (!this.isCancel) {
          this.$message.error('请选择是否作废!')
          return false
        }
        console.log("isCancel",this.isCancel)
        this.$refs.modalForm.isCancel = this.isCancel
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        // 把子表数据带进去
        this.loadList(this.dataSource)
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd() {
        if (!this.isCancel) {
          this.$message.error('请选择是否作废!')
          return false
        }
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.isCancel = this.isCancel
        // 把子表数据带进去
        this.loadList(this.dataSource)
        this.$refs.modalForm.disableSubmit = false
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.dragResizeColumns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.dragResizeColumns = cols
          }
        }
      },
      dataOne(data, flag) {
        let handleflag = true;
        console.log("this.dataSource",this.dataSource)
        for (let i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i].id == data.id) {
            console.log("datalist",data)
            this.dataSource.splice(i, 1, data);
            handleflag = false;
          }
        }
        if (handleflag) {
          this.dataSource.push(data);
        }
        this.onData()
      },
      submitForm() {
        return this.dataSource
      },
      onData() {
        console.log("onData",this.dataSource)
        this.$emit('taxRateDetail', this.dataSource);
      },
      handleCopy: function (record) {
        let model = Object.assign({}, record);
        model.id = parseInt(Math.random() * 1000000000000);
        this.dataSource.push(JSON.parse(JSON.stringify(model)))
        // this.dataOne(data, true)
        // 把子表数据带进去
        this.onData()
        this.loadList(this.dataSource)
      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },
      // 每次点击新增编辑重新加载发票信息子表
      loadList(list) {
        this.$refs.modalForm.loadList(list);
      },
      // 开票信息是否隐藏
      hiddenKpButton(auth){
        // 如果是财务部开票人 忽略其他两个条件 如果是其他节点 则使用 disabled || isDisabledAuth('erpFinanceInvoiceHandleRecord:add')
        if(!this.kpButtonDisabled){
          return this.kpButtonDisabled;
        }else{
          return  this.disabled || this.isDisabledAuth(auth);
        }
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
